package com.xhwl.centiotdata.handler.alarm.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhwl.centiotdata.handler.alarm.AlarmHandler;
import com.xhwl.centiotdata.pojo.constant.DaHuaIccConstant;
import com.xhwl.common.dto.cent.alarm.AlarmIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.dto.dahua.SecurityDaHuaDTO;
import com.xhwl.centiotdata.service.integrateconfig.AlarmIntegrationConfig;
import com.xhwl.centiotdata.suppliersystem.dahuaIcc.GeneralDaHuaIccHandler;
import com.xhwl.centiotdata.utils.RedisUtils;
import com.xhwl.centiotdata.utils.UploadUtils;
import com.xhwl.common.constant.cent.alarm.AlarmConstant;
import com.xhwl.common.dto.cent.alarm.dahuaicc.ICCDeviceDetailResult;
import com.xhwl.common.dto.cent.alarm.dahuaicc.ICCResult;
import com.xhwl.common.dto.cent.alarm.dahuaicc.subscribe.ICCAlarmResult;
import com.xhwl.common.dto.cent.alarm.dahuaicc.subscribe.ICCEventResult;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.enums.ProductEnum;
import com.xhwl.common.enums.alarm.ICCEventCategoryEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.alarm.AlarmLog;
import com.xhwl.common.pojo.cent.alarm.AlarmManagement;
import com.xhwl.common.query.cent.device.DevicePageQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Author Leon
 * @Description: TODO
 * @Date: 2022/5/9 14:15
 */
@Component
@Slf4j
public class DahuaICCReceiveHandler extends AlarmHandler {

    @Autowired
    GeneralDaHuaIccHandler generalDaHuaIccHandler;

    @Autowired
    AlarmIntegrationConfig alarmIntegrationConfig;

    @Override
    public void afterPropertiesSet() throws Exception {
        // AlarmFactory.register("HaiKangReceive",this);
    }

    public ResultJson dahuaICCReceive(String receiveContent, Integer rowId) {
        log.info("====收到 大华ICC 告警消息 ===: {}, rowId: {}", receiveContent, rowId);
        AlarmLog alarmLog = new AlarmLog();
        alarmLog.setTag("dahuaicc_alarm");
        alarmLog.setContent(receiveContent);
        alarmLog.setPushTime(new Date());
        centAlarmService.insert(alarmLog);
        Map<String, String> entries = redisTemplate.opsForHash().entries(RedisUtils.format(ProductEnum.DAHUA_ICC.getId()));
        ICCEventResult iccEventResult = JSONObject.parseObject(receiveContent, ICCEventResult.class);
        AlarmIntegrationConfigDTO alarmIntegrationConfigDTO = alarmIntegrationConfig.getIntegrationConfigById(rowId);
        // 报警消息
        if (Objects.equals(iccEventResult.getCategory(), ICCEventCategoryEnum.ALARM.getCode())) {
            ICCAlarmResult iccAlarmResult = JSONObject.parseObject(iccEventResult.getInfo(), ICCAlarmResult.class);
            log.info("icc 报警消息: {}", iccAlarmResult.toString());
            Integer alarmType = iccAlarmResult.getAlarmType();
            String alarmPicture = iccAlarmResult.getAlarmPicture();
            String thirdDeviceId = "";
            // 设备
            String token = alarmIntegrationConfigDTO.getToken();
            List<String> thirdDeviceIdList = new ArrayList<>();
            if (Objects.equals(iccAlarmResult.getNodeType(), 1)) {
                try {
                    String nodeCode = iccAlarmResult.getNodeCode();
                    Map<String, Object> param = new HashMap<>();
                    String url = alarmIntegrationConfigDTO.getIpAndPort() +
                            DaHuaIccConstant.DEVICE_DETAIL_URL.replace("{deviceCode}", nodeCode);
                    String iccRes = HttpRequest.get(url)
                            .header("Authorization", "bearer " + token)
                            .execute()
                            .body();
                    log.info("大华icc设备详情: {}", iccRes);
                    ICCResult iccResult = JSONObject.parseObject(iccRes, ICCResult.class);
                    if (Objects.equals(iccResult.getCode(), "0")) {
                        ICCDeviceDetailResult iccDeviceDetailResult = JSONObject.parseObject(iccResult.getData(), ICCDeviceDetailResult.class);
                        thirdDeviceIdList = Optional.ofNullable(iccDeviceDetailResult.getUnits())
                                .map(list -> {
                                    List<String> codeList = new ArrayList<>();
                                    for (int i = 0; i < list.size(); i++) {
                                        ICCDeviceDetailResult.Unit unit = list.get(i);
                                        if (Objects.nonNull(unit) && CollectionUtils.isNotEmpty(unit.getChannels())) {
                                            for (int j = 0; j < unit.getChannels().size(); j++) {
                                                ICCDeviceDetailResult.Channel channel = unit.getChannels().get(j);
                                                if (StringUtils.isNoneBlank(channel.getChannelCode())) {
                                                    codeList.add(channel.getChannelCode());
                                                }
                                            }
                                        }
                                    }
                                    return codeList;
                                })
                                .orElseThrow(() -> new BusinessException("====================》设备通道不存在《================"));
                    } else {
                        log.error("获取设备详情失败，{}", iccResult);
                    }
                } catch (Exception e) {
                    log.error("获取设备通道失败，{}", e);
                }
            }
            // 通道
            if (Objects.equals(iccAlarmResult.getNodeType(), 2)) {
                thirdDeviceId = iccAlarmResult.getNodeCode();
            }
            if (StringUtils.isNoneBlank(thirdDeviceId)) {
                thirdDeviceIdList.add(thirdDeviceId);
            }

            DevicePageQuery devicePageQuery = new DevicePageQuery();
            devicePageQuery.setThirdDeviceIdList(thirdDeviceIdList);
            devicePageQuery.setProjectId(alarmIntegrationConfigDTO.getProjectId());
            Page<DeviceDTO> deviceDTOPage = deviceCentService.pageDevice(null, devicePageQuery);
            DeviceDTO deviceDTO = Optional.ofNullable(deviceDTOPage).map(Page::getRecords)
                    .filter(item -> CollectionUtils.isNotEmpty(item))
                    .map(item -> item.get(0)).orElseThrow(() -> new BusinessException("====================》设备不存在《================"));
            thirdDeviceId = deviceDTO.getThirdDeviceId();

            if (StringUtils.isBlank(thirdDeviceId)) {
                throw new BusinessException("====================》告警消息不存在设备通道《================");
            }

            log.info("=================== thirdDeviceId，{}", thirdDeviceId);
            if (StringUtils.isNotBlank(entries.get(alarmType.toString()))) {
                AlarmManagement alarmManagement = new AlarmManagement();

                try {
                    // 拼接地址
                    if (StringUtils.isNoneBlank(alarmPicture)) {
                        log.info("获取icc token，{}", token);
                        alarmPicture = alarmIntegrationConfigDTO.getIpAndPort()
                                + DaHuaIccConstant.OSS_URI
                                .replace("{uri}", alarmPicture)
                                .replace("{token}", token);
                        String pictureUrl = UploadUtils.uploadImg(alarmPicture);
                        alarmManagement.setImgUrl(pictureUrl);
                    } else {
                        log.error("icc告警图片不存在");
                    }
                } catch (Exception e) {
                    log.error("icc告警图片上传失败====================>ThirdDeviceId:{}======>alarmType:{}",
                            thirdDeviceId, alarmType);
                    log.error("拼接地址为===============》{}", alarmPicture);
                    log.error("上传icc告警图片失败: {}", e);
                }
                alarmManagement.setAlarmTime(new Date());
                alarmManagement.setDeviceId(deviceDTO.getId());
                alarmManagement.setProjectId(deviceDTO.getProjectId());
                alarmManagement.setAlarmInventoryCode(entries.get(alarmType.toString()));
                sendMq(AlarmConstant.DAHUA_ICC_ALARM_TOPIC, alarmManagement);
            } else {
                log.error("大华icc厂商告警类型未配置: {}", alarmType);
            }
        }
        // 设备状态告警
        if (Objects.equals(iccEventResult.getCategory(), ICCEventCategoryEnum.STATE.getCode())) {
            ICCAlarmResult iccAlarmResult = JSONObject.parseObject(iccEventResult.getInfo(), ICCAlarmResult.class);
            log.info("icc 状态告警: {}", iccAlarmResult.toString());
        }

        return ResultJson.success();
    }
}

